package chapter1;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 第一周第二个作业
 */
public class Chapter1Task2 extends ClassLoader {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Object obj = new Chapter1Task2().findClass("Hello").newInstance();
        Method method = obj.getClass().getDeclaredMethod("hello");
        method.invoke(obj);
    }

    @Override
    protected Class<?> findClass(String name) {
        try {
            byte[] fileContent = decodeHelloXlass("src/main/resources/Hello.xlass");
            return defineClass(name, fileContent, 0, fileContent.length);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将HelloXlass中的文件通过255-字节的方式解出来
     * @param filePath
     * @return
     * @throws IOException
     */
    public byte[] decodeHelloXlass(String filePath) throws IOException {
        File file = new File("src/main/resources/Hello.xlass");
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int fileByte;
        int offset = 0;
        while ((fileByte = fi.read())!=-1){
            buffer[offset] = (byte)(255 - fileByte);
            offset++;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
}
